import React, { Component } from 'react'
import { Form, Input, Icon, Button, Spin, message } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { http } from '../../lib'
import qs from 'qs'
import { IUaaTokenData, IUaaAppInfo } from '../../lib/types'
import './Login.scss'
import { notification } from 'antd'
import { uaaApp } from '../../lib/core/uaaApp'
import Captcha from 'react-captcha-code'
const logo = require('../../../public/image/logo.png')

class Login extends Component<ILoginProps, ILoginState> {
  private authorization: IUaaTokenData = {} as IUaaTokenData
  private agentInfo: any
  private isInitPassword: boolean

  constructor(props: ILoginProps) {
    super(props)
    this.state = {
      timestamp: '',
      verifyCodeImg: '',
      verificationCode: '',
      codeText: '',
      loading: false,
      showLoadingPage: true,
      showInitPage: false,
      startPassword: "",
      initStartPassword: "Lzlj@2023",
    }
    if (this.props.loginApiBaseUrl !== null && this.props.loginApiBaseUrl !== undefined) {
      http.defaults.baseURL = this.props.loginApiBaseUrl
    }
  }

  public componentDidMount() {
    this.getVerifyCode()
    const querys: any = qs.parse(window.location.href.split('?')[1])
    console.log(querys)
    if (querys.message) {
      this.openNotificationWithIcon('error', querys.message)
    }
    if (querys.Authorization && querys.Authorization.length > 0) {
      const authorization = {
        accessToken: querys.Authorization,
        accessTokenExpireTime: '' + new Date().getTime() * 24 * 3600 * 1000,
        refreshToken: querys.Authorization,
        refreshTokenExpireTime: '' + new Date().getTime() * 24 * 3600 * 1000,
      }
      this.authorization = authorization
      // 登录账号是否初始密码
      this.isInitPassword = querys.initPassword
      this.getMyInfo()
    } else {
      this.setState({
        showLoadingPage: false,
      })
    }
  }

  public onStartSubmit = () => {
    let { startPassword, initStartPassword } = this.state
    if (startPassword === initStartPassword) {
      this.setState({
        showInitPage: false
      })
    } else {
      message.error('登录失败,请重试！！！');
    }
  }

  public openNotificationWithIcon = (type, message) => {
    notification[type]({
      message: '提示',
      description: message,
    })
  }
  public render() {
    const { getFieldDecorator } = this.props.form

    return (
      <div className="page-login">
        {this.state.showInitPage ?
          <div className="login-panel login-start-panel">
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="密码"
              value={this.state.startPassword}
              onChange={(v) => this.setState({
                startPassword: v.target.value
              })}
            />
            <Button
              className="login-btn"
              type="primary"
              onClick={this.onStartSubmit}
            >
              登录
            </Button>
          </div>
          : this.state.showLoadingPage ? (
            <Spin size="large" />
          ) : (
            <div className="login-panel">
              <img className="login-logo" src={logo} alt="经销商门户后台管理系统" />
              <h1 className="login-title">经销商门户后台管理系统</h1>
              <Form onSubmit={this.handleSubmit} className="login-form">
                <Form.Item>
                  {getFieldDecorator('username', {
                    initialValue: this.props.username || '',
                    rules: [{ required: true, message: '请输入账号' }],
                  })(
                    <Input
                      prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                      placeholder="账号"
                      onChange={this.userNameChange}
                    />
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('password', {
                    initialValue: this.props.password || '',
                    rules: [{ required: true, message: '请输入登录密码' }],
                  })(
                    <Input
                      prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                      type="password"
                      placeholder="密码"
                    />
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('vercode', {
                    rules: [{ required: true, message: '请输入验证码' }],
                  })(
                    <div className="vercode-box">
                      <Input
                        value={this.state.codeText}
                        prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        placeholder="验证码"
                        onChange={e => this.setState({ codeText: e.target.value })}
                      />
                      {this.state.verifyCodeImg ? (
                        <img
                          className="vercode-img"
                          alt="加载中"
                          onClick={() => this.getVerifyCode()}
                          src={this.state.verifyCodeImg}
                        />
                      ) : (
                        <Captcha charNum={4} code={'8888'} />
                      )}
                    </div>
                  )}
                </Form.Item>

                <Form.Item style={{ textAlign: 'center', margin: '0' }}>
                  <Button
                    loading={this.state.loading}
                    style={{ lineHeight: '1' }}
                    type="primary"
                    htmlType="submit"
                    className="login-form-button"
                  >
                    登录
                  </Button>
                </Form.Item>
              </Form>
            </div>
          )}
      </div>
    )
  }

  private randomText() {
    const text = 'abcdefghijklmnopqrstuvwxyz0123456789'
    const rdmIndex = text => (Math.random() * text.length) | 0
    const len = 4
    let rdmString = ''
    for (; rdmString.length < len; rdmString += text.charAt(rdmIndex(text)));
    return rdmString
  }

  private clearVerifyCode = () => {
    this.setState(
      {
        codeText: '',
      },
      () => {
        this.getVerifyCode()
      }
    )
  }

  protected getVerifyCode = () => {
    this.setState(
      {
        timestamp: Date.now(),
      },
      () => {
        http
          .get('/api/v1/user/initVerifyCode', {
            params: {
              keyFlag: this.state.timestamp,
            },
          })
          .then(res => {
            let { imgBase64, verificationCode } = res.data
            this.setState({
              verifyCodeImg: `data:image/jpg;base64,` + imgBase64,
              verificationCode,
            })
          })
      }
    )
  }

  protected handleSubmit = e => {
    e.preventDefault()
    let { verificationCode, codeText, timestamp } = this.state
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        if (codeText.replace(/\s*/g, '') === '') {
          message.error('请输入验证码！')
          return
        } else if (codeText !== verificationCode) {
          this.clearVerifyCode()
          message.error('验证码输入有误！请重新输入。')
          return
        }
        this.setState({ loading: true })
        let { ...user } = values
        user.verificationCode = verificationCode
        user.keyFlag = timestamp
        delete user.vercode
        http
          .post<ILoginRes>('/login', user)
          .then(res => {
            const authorization = {
              accessToken: res.data?.token,
              accessTokenExpireTime: '' + new Date().getTime() * 24 * 3600 * 1000,
              refreshToken: res.data?.token,
              refreshTokenExpireTime: '' + new Date().getTime() * 24 * 3600 * 1000,
            }
            const agentList = res.data?.agentList
            this.agentInfo = agentList ? agentList[0] : undefined
            this.authorization = authorization
            // 登录账号是否初始密码
            this.isInitPassword = res.data?.initPassword
            this.getMyInfo()
          })
          .catch(() => {
            this.clearVerifyCode()
            this.setState({ loading: false })
          })
      }
    })
  }

  private getMyInfo = () => {
    http
      .get<IUaaAppInfo>('/api/v1/user/getMenu', { headers: { Authorization: this.authorization.accessToken } })
      .then((res: any) => {
        const { userInfo, menuList } = res.data
        const uaaSysInfo = {
          profile: userInfo,
          webUrls: {},
          urls: {},
          authorities: [],
          attributes: '',
          generalMenus: [
            {
              application: 'LZLJ',
              customId: 'LZLJ',
              icon: 'unlock',
              orderIndex: 1,
              text: '经销商门户管理系统',
              type: 'GROUP',
              items: [
                {
                  application: 'LZLJ',
                  type: 'INNER_LINK',
                  text: '首页',
                  customId: 'home_page',
                  icon: 'home',
                  orderIndex: 0,
                  link: null,
                  url: null,
                  webUrl: null,
                },
                ...menuList,
              ],
            },
          ],
        }
        uaaApp.setToken(this.authorization)
        uaaApp.setSysInfo(uaaSysInfo as IUaaAppInfo)
        if (this.isInitPassword) {
          // 登录密码是初始密码
          uaaApp.setIsInitialPwd('true')
        }
        window.location.href = '/'
      })
      .finally(() => {
        this.setState({ loading: false })
      })
  }

  public userNameChange = e => {
    let val = e.target.value
    val = val.replace(/\s+/g, '')
    e.target.value = val
  }
}

interface ILoginProps extends FormComponentProps {
  loginApiBaseUrl: string
  username?: string
  password?: string
}

interface ILoginState {
  timestamp: number | string
  verifyCodeImg: string
  verificationCode: string
  loading?: boolean
  showLoadingPage?: boolean
  showInitPage?: boolean
  startPassword?: string
  initStartPassword?: string
  codeText?: string
}

interface ILoginRes {
  ticket: string
  token: string
  agentList: any[]
  initPassword: boolean
}

export default Form.create<ILoginProps>()(Login)
